package com.example.newsapp.activity;

import static com.example.newsapp.constant.NetConstant.BASE_URL;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;

import com.bumptech.glide.Glide;
import com.example.newsapp.adapter.NewsAdapter;
import com.example.newsapp.model.NewsItem;
import com.example.newsapp.model.Result;
import com.example.newsapp.model.request.LikeRequest;
import com.example.newsapp.model.resultData.NewsDetailResultData;
import com.example.newsapp.utils.DBHelper;
import com.example.newsapp.R;
import com.example.newsapp.model.Comment;
import com.example.newsapp.model.UserNewsItem;
import com.example.newsapp.utils.HttpUtil;
import com.example.newsapp.utils.UserSessionUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

public class NewsDetailActivity extends AppCompatActivity {
    private ImageView btnBack, newsImage, btnLike;
    private TextView newsTitle, newsInfo, newsContent, commentCount;
    private LinearLayout commentsContainer;
    private EditText etComment;
    private Button btnSend;
    private NestedScrollView scrollView;
    private List<Comment> commentList;
    private boolean isLiked = false;
    private boolean isLoggedIn = false;
    private SimpleDateFormat dateFormat;
    private Long replyToCommentUserId = null;
    private Long parentId = null;
    private String replyToUserName = null;
    private View rootView;
    private View maskView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);
        Log.d("newsDetail", "这是测试新闻详情");
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        initViews();
        setupListeners();
        loadNewsData();
        loadComments();
    }

    private void initViews() {
        rootView = findViewById(android.R.id.content);
        btnBack = findViewById(R.id.btnBack);
        newsImage = findViewById(R.id.newsImage);
        newsTitle = findViewById(R.id.newsTitle);
        newsInfo = findViewById(R.id.newsInfo);
        newsContent = findViewById(R.id.newsContent);
        commentCount = findViewById(R.id.commentCount);
        commentsContainer = findViewById(R.id.commentsContainer);
        etComment = findViewById(R.id.etComment);
        btnSend = findViewById(R.id.btnSend);
        btnLike = findViewById(R.id.btnLike);
        scrollView = findViewById(R.id.scrollView);
        maskView = findViewById(R.id.maskView);

        isLoggedIn = UserSessionUtil.isLoggedIn(NewsDetailActivity.this);

        // 设置触摸事件监听
        rootView.setOnTouchListener((v, event) -> {
            if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
                resetCommentState();
                return true;
            }
            return false;
        });

        scrollView.setOnTouchListener((v, event) -> {
            if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
                resetCommentState();
                return true;
            }
            return false;
        });

        // 设置遮罩层点击事件
        maskView.setOnClickListener(v -> resetCommentState());
    }

    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());

        btnLike.setOnClickListener(v -> {
            if (!isLoggedIn) {
                startActivity(new Intent(this, LoginActivity.class));
                return;
            }
            Intent intent = getIntent();
            Integer newsId = intent.getIntExtra("news_id", -1);
            requestLiked(newsId.longValue(), !isLiked);


        });

        btnSend.setOnClickListener(v -> {
            if (!isLoggedIn) {
                startActivity(new Intent(this, LoginActivity.class));
                return;
            }
            String content = etComment.getText().toString().trim();
            if (content.isEmpty()) {
                Toast.makeText(this, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            submitComment(content);
        });

        // 设置评论输入框的点击监听
        etComment.setOnClickListener(v -> {
            // 防止点击事件传递到根视图
            v.requestFocus();
        });

        // 监听输入框焦点变化
        etComment.setOnFocusChangeListener((v, hasFocus) -> {
            maskView.setVisibility(hasFocus ? View.VISIBLE : View.GONE);
        });

        // 防止评论区域的点击事件传递到根视图
        commentsContainer.setOnTouchListener((v, event) -> {
            // 只有当输入法显示时，才拦截点击事件
            if (etComment.hasFocus()) {
                resetCommentState();
                return true;
            }
            return false;
        });
    }

    private void resetCommentState() {
        // 如果用户没有输入任何内容，完全重置状态
        if (etComment.getText().toString().trim().isEmpty()) {
            parentId = null;
            replyToCommentUserId = null;
            replyToUserName = null;
            etComment.setText("");
            etComment.setHint("写评论...");
        }
        etComment.clearFocus();
        // 隐藏遮罩层
        maskView.setVisibility(View.GONE);
        // 关闭输入法
        android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) getSystemService(
                android.content.Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(etComment.getWindowToken(), 0);
        }
    }

    private void loadNewsData() {
        Intent intent = getIntent();
        Integer newsId = intent.getIntExtra("news_id", -1);
        String title = intent.getStringExtra("news_title");
        String time = intent.getStringExtra("news_time");
        String imageUrl = intent.getStringExtra("news_image");
        String author = intent.getStringExtra("news_author");

        newsTitle.setText(title);
        newsInfo.setText(time + " | 作者：" + author);

        Glide.with(this).load(BASE_URL + imageUrl).into(newsImage);

        if (newsId == -1) {
            showToast("id不能为空,无法获取新闻正文");
            return;
        }


        requestContent(newsId);


        int userId = UserSessionUtil.getUserId(this);

        if (userId == -1) {
            //新闻id为空或用户未登录，不记录
            return;
        }
        // 插入或更新到浏览记录
        DBHelper dbHelper = new DBHelper(this);
        UserNewsItem userNewsItem = new UserNewsItem(newsId, title, time, imageUrl, author, userId);
        dbHelper.insertOrUpdateHistory(userNewsItem);

    }

    private void requestContent(Integer newsId) {
        String requestUrl = BASE_URL + "/news/" + newsId;
        Type type = new TypeToken<Result<NewsDetailResultData>>() {
        }.getType();

        HttpUtil.request(NewsDetailActivity.this, requestUrl, "GET", null, type, new HttpUtil.Callback<Result<NewsDetailResultData>>() {
            @Override
            public void onSuccess(Result<NewsDetailResultData> result) {
                handlerNewsDetailResponse(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("查询出错");
            }
        });

    }

    private void requestLiked(Long newsId, Boolean isLiked) {
        LikeRequest likeRequest = new LikeRequest(newsId, isLiked);
        String requestUrl = BASE_URL + "/news/like";
        Type resultType = new TypeToken<Result<String>>() {
        }.getType();

        HttpUtil.request(NewsDetailActivity.this, requestUrl, "PUT", likeRequest, resultType, new HttpUtil.Callback<Result<String>>() {
            @Override
            public void onSuccess(Result<String> result) {
                handleLikedResponse(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("网络异常：" + e.getMessage());
            }
        });
    }

    private void handlerNewsDetailResponse(Result<NewsDetailResultData> response) {
        if (response == null) {
            showToast("服务器响应异常");
            return;
        }

        if (response.getCode() == 1 && response.getData() != null) {
            NewsDetailResultData detail = response.getData();
            isLiked = detail.getLike();
            btnLike.setImageResource(isLiked ? R.drawable.ic_liked : R.drawable.ic_like);
            newsContent.setText(detail.getContext());
        } else {
            String errorMsg = response.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) errorMsg = "未知错误";
            showToast("获取+" + newsTitle.getText() + "正文失败：" + errorMsg);
        }
    }

    private void handleLikedResponse(Result<String> result) {
        if (result == null) {
            showToast("服务器响应异常");
            return;
        }

        if (result.getCode() == 1) {
            isLiked = !isLiked;
            btnLike.setImageResource(isLiked ? R.drawable.ic_liked : R.drawable.ic_like);
            Toast.makeText(this, isLiked ? "已点赞" : "已取消点赞", Toast.LENGTH_SHORT).show();
        } else {
            String errorMsg = result.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) errorMsg = "未知错误";
            showToast(errorMsg);
        }
    }

    private void loadComments() {
        Intent intent = getIntent();
        Integer newsId = intent.getIntExtra("news_id", -1);
        requestComments(newsId);
    }

    private void updateCommentsList() {
        commentsContainer.removeAllViews();
        int totalComments = 0;

        LayoutInflater inflater = LayoutInflater.from(this);
        for (Comment comment : commentList) {
            totalComments++;

            View commentView = inflater.inflate(R.layout.item_comment, commentsContainer, false);

            View commentArea = commentView.findViewById(R.id.commentArea);
            TextView userName = commentView.findViewById(R.id.userName);
            TextView commentTime = commentView.findViewById(R.id.commentTime);
            TextView commentContent = commentView.findViewById(R.id.commentContent);
            ImageView userAvatar = commentView.findViewById(R.id.userAvatar);
            TextView btnReply = commentView.findViewById(R.id.btnReply);
            LinearLayout repliesContainer = commentView.findViewById(R.id.repliesContainer);

            userName.setText(comment.getUserName());
            //TODO
  /*          int userId = UserSessionUtil.getUserId(NewsDetailActivity.this);
            if(userId == comment.getUserId()){
                userName.setText("当前用户");
            }*/
            commentTime.setText(dateFormat.format(new Date(comment.getTimestamp())));
            commentContent.setText(comment.getContent());

            // 设置评论一级评论点击事件
            View.OnClickListener replyListener = v -> {
                if (!isLoggedIn) {
                    startActivity(new Intent(this, LoginActivity.class));
                    return;
                }
                parentId = comment.getId();
                replyToCommentUserId = comment.getUserId();
                replyToUserName = comment.getUserName();
                etComment.setHint("回复 " + replyToUserName);
                etComment.requestFocus();
                // 显示遮罩层
                maskView.setVisibility(View.VISIBLE);
                // 显示输入法
                android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) getSystemService(
                        android.content.Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.showSoftInput(etComment, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
                }
            };

            commentArea.setOnClickListener(replyListener);
            btnReply.setOnClickListener(replyListener);

            // 添加回复列表
            if (comment.getReplies() != null && !comment.getReplies().isEmpty()) {
                for (Comment reply : comment.getReplies()) {
                    totalComments++;
                    View replyView = inflater.inflate(R.layout.item_comment_reply, repliesContainer, false);

                    View replyArea = replyView.findViewById(R.id.replyArea);
                    TextView replyUserName = replyView.findViewById(R.id.userName);
                    TextView replyTime = replyView.findViewById(R.id.commentTime);
                    TextView replyContent = replyView.findViewById(R.id.commentContent);
                    ImageView replyUserAvatar = replyView.findViewById(R.id.userAvatar);

                    replyUserName.setText(reply.getUserName());
                    replyTime.setText(dateFormat.format(new Date(reply.getTimestamp())));
                    replyContent.setText("回复 @" + reply.getReplyToUserName() + ": " + reply.getContent());

                    // 设置回复的点击事件
                    replyArea.setOnClickListener(v -> {
                        if (!isLoggedIn) {
                            startActivity(new Intent(this, LoginActivity.class));
                            return;
                        }
                        parentId = comment.getId();
                        replyToCommentUserId = reply.getUserId();  //回复的用户的id
                        replyToUserName = reply.getUserName(); // @二级评论的用户
                        etComment.setHint("回复 " + replyToUserName);
                        etComment.requestFocus();
                        // 显示遮罩层
                        maskView.setVisibility(View.VISIBLE);
                        // 显示输入法
                        android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) getSystemService(
                                android.content.Context.INPUT_METHOD_SERVICE);
                        if (imm != null) {
                            imm.showSoftInput(etComment, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
                        }
                    });

                    repliesContainer.addView(replyView);
                }
            }

            commentsContainer.addView(commentView);
        }

        commentCount.setText(String.valueOf(totalComments));
    }

    private void submitComment(String content) {

        int userId = UserSessionUtil.getUserId(NewsDetailActivity.this);

        Intent intent = getIntent();
        Integer newsId = intent.getIntExtra("news_id", -1);
        Comment newComment = null;
        if (parentId != null) {
            // 提交回复
            for (Comment comment : commentList) {
                if (comment.getId().equals(parentId)) {
                    newComment = new Comment(
                            null, //评论唯一id 后端返回？
                            Long.valueOf(userId),
                            "",
                            "",
                            content,
                            parentId,
                            replyToCommentUserId,
                            replyToUserName,
                            System.currentTimeMillis());


//                    reply.setParentId(parentId);
//                    comment.addReply(reply);
                    break;
                }
            }
        } else {
            // 提交新评论
             newComment = new Comment(
                    null,
                    Long.valueOf(userId),
                    "",
                    "",
                    content,
                    System.currentTimeMillis());
            //commentList.add(0, newComment);
        }
        requestSaveComment(newsId,newComment);


    }

    private void requestSaveComment(Integer newsId,Comment comment) {
        String requestUrl = BASE_URL + "/Comments/"+newsId ;
        Type resultType = new TypeToken<Result<String>>() {
        }.getType();
        HttpUtil.request(NewsDetailActivity.this,requestUrl, "POST", comment, resultType, new HttpUtil.Callback<Result<String>>() {
            @Override
            public void onSuccess(Result<String> result) {
                handleSaveCommentResponse(result,newsId);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("查询出错");
            }
        });
    }

    private void handleSaveCommentResponse(Result<String> response,Integer newsId){
        if (response == null) {
            showToast("服务器响应异常");
            etComment.setText("");
            resetCommentState();
            return;
        }

        if (response.getCode() == 1 && response.getData() != null) {
            Toast.makeText(this, response.getData(), Toast.LENGTH_SHORT).show();
            //重新获取评论 刷新数据
            requestComments(newsId);

        } else {
            String errorMsg = response.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) errorMsg = "未知错误";
            showToast("评论失败：" + errorMsg);
        }
        etComment.setText("");
        resetCommentState();
    }

    private void requestComments(Integer newsId) {
        String requestUrl = BASE_URL + "/Comments/"+newsId ;
        Type resultType = new TypeToken<Result<List<Comment>>>() {
        }.getType();
        HttpUtil.request(NewsDetailActivity.this,requestUrl, "GET", null, resultType, new HttpUtil.Callback<Result<List<Comment>>>() {
            @Override
            public void onSuccess(Result<List<Comment>> result) {
                handleCommentResponse(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("查询出错");
            }
        });
    }

    private void handleCommentResponse(Result<List<Comment>> response) {
        if (response == null) {
            showToast("服务器响应异常");
            return;
        }

        if (response.getCode() == 1 && response.getData() != null) {
            commentList = response.getData();
            updateCommentsList();
        } else {
            String errorMsg = response.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) errorMsg = "未知错误";
            showToast("获取+" + "评论列表失败：" + errorMsg);
        }
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}